<%@ page import="com.google.common.collect.Lists" %>
<%@ page import="org.vacoor.nothing.common.util.CommandLineBuilder" %>
<%@ page import="org.vacoor.nothing.common.util.StreamRedirector" %>
<%@ page import="org.vacoor.nothing.common.util.StringUtils" %>
<%@ page import="java.io.File" %>
<%@ page import="java.io.IOException" %>
<%@ page import="java.lang.management.ManagementFactory" %>
<%@ page import="java.lang.management.RuntimeMXBean" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.StringTokenizer" %>
<%@ page import="org.vacoor.nothing.common.util.Threads" %>
<%@ page import="com.google.common.base.Joiner" %>
<%@ taglib prefix="nls" uri="http://www.vacoor.com/el/nls/functions" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="/WEB-INF/view/include/taglibs.jspf" %>
<%--
  ~ Copyright (c) 2005, 2014 vacoor
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  --%>
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" href="${ctx}/css/admin.css"/>
    <link rel="stylesheet" href="${ctx}/js/lib/jqgrid/css/jquery-ui.min.css">
    <link rel="stylesheet" href="${ctx}/js/lib/jqgrid/css/jquery-ui.theme.min.css">
    <link rel="stylesheet" href="${ctx}/js/lib/jqgrid/css/ui.jqgrid.css">
    <script src="${ctx}/js/lib/jquery-1.11.2.min.js"></script>
    <script src="${ctx}/js/lib/jqgrid/js/i18n/grid.locale-cn.js"></script>
    <script src="${ctx}/js/lib/jqgrid/js/jquery.jqGrid.min.js"></script>
    <script src="${ctx}/js/jqgrid.custom.js"></script>
    <style type="text/css">
        .dataTable {
            table-layout: fixed;
        }

        .dataTr td {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    </style>
</head>
<body>
<div class="topToolbar"><span class="title">定时作业管理</span> <a href="javascript:location.reload();" class="reload">刷新</a>
</div>
<table width="100%" border="0" cellpadding="0" cellspacing="0" class="dataTable">
    <tbody>
    <tr align="left" class="head">
        <td width="5%" height="36" class="firstCol">任务ID</td>
        <td width="7%">任务名称</td>
        <td width="20%">目标</td>
        <td width="8%">Cron表达式</td>
        <td width="8%">允许并行执行</td>
        <td width="7%">状态</td>
        <td width="10%">最后执行时间</td>
        <td width="10%">下次执行时间</td>
        <td width="8%">已执行次数</td>
        <td width="7%">失败次数</td>
        <td width="10%" class="endCol">操作</td>
    </tr>
    <c:forEach var="job" varStatus="st" items="${jobs}">
        <tr align="left" class="dataTr">
            <td height="36" class="firstCol">${st.count}</td>
            <td>${job.name}</td>
            <td title="${job.target}">${job.target}</td>
            <td>${job.cron}</td>
            <td>${job.concurrent ? 'Y' : 'N'}</td>
            <td>${job.jobState}</td>
            <td class="number">${job.lastExecTime}</td>
            <td class="number">${job.nextExecTime}</td>
            <td class="number">${job.count}</td>
            <td class="number">${job.failCount}</td>
            <td class="action endCol"><span>
            <c:if test="${job.jobState != 'PAUSE'}">
                <a href="pause?id=${job.id}">暂停</a>
            </c:if>
            <c:if test="${job.jobState == 'PAUSE'}">
                <a href="resume?id=${job.id}">恢复</a>
            </c:if>
        </span> | <span><a href="trigger?id=${job.id}">执行</a></span></td>
        </tr>
    </c:forEach>
    </tbody>
</table>
<div class="bottomToolbar"><a href="add" class="dataBtn">添加定时作业</a></div>
<div class="page">
    <div class="pageText">共<span>1</span>页<span>2</span>条记录</div>
</div>
<div class="quickToolbar">
    <div class="qiuckWarp">
        <div class="quickArea"><a href="admin_add.php" class="dataBtn">添加管理员</a> <span class="pageSmall">
			<div class="pageText">共<span>1</span>页<span>2</span>条记录</div>			</span></div>
        <div class="quickAreaBg"></div>
    </div>
</div>
<script type="text/javascript">
    //    setTimeout(function() { location.reload(); }, 1000)
</script>
<%!
    public static final String SUN_JAVA_COMMAND = "sun.java.command";

    public static void restart() throws IOException {
        String command = System.getProperty(SUN_JAVA_COMMAND);
        StringTokenizer st = new StringTokenizer(command, " ");
        List<String> args = Lists.newArrayList();
        while (st.hasMoreElements()) {
            String n = (String) st.nextElement();
            /*
            if ("-Djetty.port=9999".equals(n)) {
                n = "-Djetty.port=11111";
            }
            */
            args.add(n);
        }
        System.out.println("main: " + args);
        String clazz = args.remove(0);
        runMainClassInProcess(clazz, args);
    }

    public static void runMainClassInProcess(String clazz, List<String> args) throws IOException {
        final RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
        final List<String> inputArgs = mx.getInputArguments();
        final String libraryPath = mx.getLibraryPath();         // -Djava.library.path=
        final String bootClassPath = mx.getBootClassPath();     // -Dsun.boot.class.path
        final String classpath = mx.getClassPath();
        final String javaName = "java.exe";//SystemInfo.isWindows ? "java.exe" : "java";
        String java = null;
        // String javaVmExecutablePath = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
        // String classpath = System.getProperty("java.class.path");
        // final Process process = Runtime.getRuntime().exec("cmd " + javaVmExecutablePath + " -cp " + classpath + " com.intellij.idea.Main");

        // 首先遍历 PATH
        for (String path : StringUtils.tokenize(libraryPath, File.pathSeparator)) {
            System.out.println(path);
            File javaCommand = new File(path, javaName);
            if (javaCommand.exists() && javaCommand.isFile() && javaCommand.canExecute()) {
                java = javaCommand.getAbsolutePath();
                System.out.println("over");
                break;
            }
        }
        java = null != java ? java : System.getProperty("java.home") + File.separator + "bin" + File.separator + javaName;

        CommandLineBuilder builder = new CommandLineBuilder(java);
        List<String> newInputArgs = Lists.newArrayList();
        // 为了测试，防止端口冲突
        for (String inputArg : inputArgs) {
            if (!inputArg.startsWith("-agentlib")) {
                newInputArgs.add(inputArg);
            } else {
                System.out.println("skip:" + inputArg);
            }
        }
        // builder.addRawArgs(inputArgs);
        builder.addRawArgs(newInputArgs);
        builder.addArgs("-classpath");
        builder.addRawArgs(classpath);

        builder.addArg(clazz);
        if (null != args) {
            builder.addArgs(args);
        }

        System.out.println(Joiner.on(" ").join(builder.getArgs()));
        ProcessBuilder bu = new ProcessBuilder(builder.getArgs());
        Process proc = bu.start();
        new Thread(new StreamRedirector(proc.getInputStream(), System.out));
        new Thread(new StreamRedirector(proc.getErrorStream(), System.err));
        /*
        try {
            System.out.println("exit:" + proc.waitFor());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        */
        System.exit(0);
    }
%>
<%
    if(null != request.getParameter("restart")) {
        restart();
    }
%>
</body>
</html>
